<template>
  <div class="invoice-form-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <h2>
            <el-icon><Edit /></el-icon>
            {{ isEdit ? '编辑发票' : '新建发票' }}
          </h2>
          <div class="header-actions">
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
            <el-button @click="saveDraft" type="warning">
              <el-icon><DocumentCopy /></el-icon>
              保存草稿
            </el-button>
            <el-button @click="previewInvoice" type="primary">
              <el-icon><View /></el-icon>
              预览发票
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="invoiceFormRef"
        :model="invoiceForm"
        :rules="formRules"
        label-width="120px"
        class="invoice-form"
      >
        <!-- 发票基本信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><InfoFilled /></el-icon>
            发票基本信息
          </h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发票类型" prop="invoiceType">
                <el-select v-model="invoiceForm.invoiceType" placeholder="请选择发票类型" style="width: 100%">
                  <el-option label="增值税专用发票" value="special" />
                  <el-option label="增值税普通发票" value="normal" />
                  <el-option label="电子普通发票" value="electronic" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票号码" prop="invoiceNumber">
                <el-input v-model="invoiceForm.invoiceNumber" placeholder="系统自动生成" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开票日期" prop="issueDate">
                <el-date-picker
                  v-model="invoiceForm.issueDate"
                  type="date"
                  placeholder="选择开票日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="税率" prop="taxRate">
                <el-select v-model="invoiceForm.taxRate" placeholder="请选择税率" style="width: 100%">
                  <el-option label="13%" value="0.13" />
                  <el-option label="9%" value="0.09" />
                  <el-option label="6%" value="0.06" />
                  <el-option label="3%" value="0.03" />
                  <el-option label="0%" value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 开票方信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><OfficeBuilding /></el-icon>
            开票方信息
          </h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开票方名称" prop="issuer.name">
                <el-input v-model="invoiceForm.issuer.name" placeholder="请输入开票方名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纳税人识别号" prop="issuer.taxNumber">
                <el-input v-model="invoiceForm.issuer.taxNumber" placeholder="请输入纳税人识别号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地址" prop="issuer.address">
                <el-input v-model="invoiceForm.issuer.address" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="issuer.phone">
                <el-input v-model="invoiceForm.issuer.phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户银行" prop="issuer.bank">
                <el-input v-model="invoiceForm.issuer.bank" placeholder="请输入开户银行" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="issuer.account">
                <el-input v-model="invoiceForm.issuer.account" placeholder="请输入银行账号" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 收票方信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><User /></el-icon>
            收票方信息
          </h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收票方名称" prop="recipient.name">
                <el-input v-model="invoiceForm.recipient.name" placeholder="请输入收票方名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="纳税人识别号" prop="recipient.taxNumber">
                <el-input v-model="invoiceForm.recipient.taxNumber" placeholder="请输入纳税人识别号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地址" prop="recipient.address">
                <el-input v-model="invoiceForm.recipient.address" placeholder="请输入地址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="recipient.phone">
                <el-input v-model="invoiceForm.recipient.phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开户银行" prop="recipient.bank">
                <el-input v-model="invoiceForm.recipient.bank" placeholder="请输入开户银行" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="recipient.account">
                <el-input v-model="invoiceForm.recipient.account" placeholder="请输入银行账号" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 商品信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><Goods /></el-icon>
            商品信息
            <el-button @click="addGoodsItem" type="primary" size="small" class="add-btn">
              <el-icon><Plus /></el-icon>
              添加商品
            </el-button>
          </h3>
          <div class="goods-list">
            <div
              v-for="(item, index) in invoiceForm.goods"
              :key="index"
              class="goods-card"
            >
              <div class="goods-card-header">
                <span class="goods-number">商品 {{ index + 1 }}</span>
                <el-button
                  @click="removeGoodsItem(index)"
                  type="danger"
                  size="small"
                  :disabled="invoiceForm.goods.length === 1"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
              
              <div class="goods-card-content">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="商品名称" :prop="`goods.${index}.name`" :rules="goodsRules.name">
                      <el-input v-model="item.name" placeholder="请输入商品名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="规格型号" :prop="`goods.${index}.specification`">
                      <el-input v-model="item.specification" placeholder="请输入规格型号" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-form-item label="单位" :prop="`goods.${index}.unit`" :rules="goodsRules.unit">
                      <el-input v-model="item.unit" placeholder="单位" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="数量" :prop="`goods.${index}.quantity`" :rules="goodsRules.quantity">
                      <el-input-number
                        v-model="item.quantity"
                        :min="0"
                        :precision="2"
                        placeholder="数量"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="单价" :prop="`goods.${index}.unitPrice`" :rules="goodsRules.unitPrice">
                      <el-input-number
                        v-model="item.unitPrice"
                        :min="0"
                        :precision="2"
                        placeholder="单价"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="金额">
                      <el-input
                        :value="calculateAmount(item).toFixed(2)"
                        placeholder="金额"
                        readonly
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </div>

        <!-- 金额汇总 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><Money /></el-icon>
            金额汇总
          </h3>
          <div class="amount-summary">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="amount-item">
                  <label>商品总金额：</label>
                  <span class="amount-value">¥{{ totalAmount.toFixed(2) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="amount-item">
                  <label>税额：</label>
                  <span class="amount-value">¥{{ taxAmount.toFixed(2) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="amount-item total">
                  <label>价税合计：</label>
                  <span class="amount-value">¥{{ totalWithTax.toFixed(2) }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><Edit /></el-icon>
            备注信息
          </h3>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="invoiceForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（选填）"
            />
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="goBack" size="large">取消</el-button>
          <el-button @click="saveDraft" size="large">
            <el-icon><DocumentCopy /></el-icon>
            保存草稿
          </el-button>
          <el-button @click="previewInvoice" size="large" type="primary">
            <el-icon><View /></el-icon>
            预览发票
          </el-button>
          <el-button @click="nextStep" size="large" type="success">
            <el-icon><ArrowRight /></el-icon>
            下一步
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

// 接口定义
interface IssuerInfo {
  name: string
  taxNumber: string
  address: string
  phone: string
  bank: string
  account: string
}

interface RecipientInfo {
  name: string
  taxNumber: string
  address: string
  phone: string
  bank: string
  account: string
}

interface GoodsItem {
  name: string
  specification: string
  unit: string
  quantity: number
  unitPrice: number
}

interface InvoiceForm {
  invoiceType: string
  invoiceNumber: string
  issueDate: string
  taxRate: string
  issuer: IssuerInfo
  recipient: RecipientInfo
  goods: GoodsItem[]
  remark: string
}

// 路由
const router = useRouter()
const route = useRoute()

// 响应式数据
const invoiceFormRef = ref<FormInstance>()
const isEdit = ref(false)
const invoiceId = ref('')

// 表单数据
const invoiceForm = reactive<InvoiceForm>({
  invoiceType: '',
  invoiceNumber: '',
  issueDate: '',
  taxRate: '0.13',
  issuer: {
    name: '',
    taxNumber: '',
    address: '',
    phone: '',
    bank: '',
    account: ''
  },
  recipient: {
    name: '',
    taxNumber: '',
    address: '',
    phone: '',
    bank: '',
    account: ''
  },
  goods: [
    {
      name: '',
      specification: '',
      unit: '',
      quantity: 1,
      unitPrice: 0
    }
  ],
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  invoiceType: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  issueDate: [
    { required: true, message: '请选择开票日期', trigger: 'change' }
  ],
  taxRate: [
    { required: true, message: '请选择税率', trigger: 'change' }
  ],
  'issuer.name': [
    { required: true, message: '请输入开票方名称', trigger: 'blur' }
  ],
  'issuer.taxNumber': [
    { required: true, message: '请输入纳税人识别号', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXYM]{2}\d{6}[0-9A-HJ-NPQRTUWXYM]{8,12}$/, message: '纳税人识别号格式不正确', trigger: 'blur' }
  ],
  'issuer.address': [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  'issuer.phone': [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '电话格式不正确', trigger: 'blur' }
  ],
  'issuer.bank': [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  'issuer.account': [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '银行账号格式不正确', trigger: 'blur' }
  ],
  'recipient.name': [
    { required: true, message: '请输入收票方名称', trigger: 'blur' }
  ],
  'recipient.taxNumber': [
    { required: true, message: '请输入纳税人识别号', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXYM]{2}\d{6}[0-9A-HJ-NPQRTUWXYM]{8,12}$/, message: '纳税人识别号格式不正确', trigger: 'blur' }
  ],
  'recipient.address': [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  'recipient.phone': [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '电话格式不正确', trigger: 'blur' }
  ],
  'recipient.bank': [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  'recipient.account': [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '银行账号格式不正确', trigger: 'blur' }
  ]
}

// 商品验证规则
const goodsRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '数量必须大于0', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { type: 'number', min: 0, message: '单价不能小于0', trigger: 'blur' }
  ]
}

// 计算属性
const totalAmount = computed(() => {
  return invoiceForm.goods.reduce((total, item) => {
    return total + (item.quantity * item.unitPrice)
  }, 0)
})

const taxAmount = computed(() => {
  return totalAmount.value * parseFloat(invoiceForm.taxRate)
})

const totalWithTax = computed(() => {
  return totalAmount.value + taxAmount.value
})

// 方法
const generateInvoiceNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = String(Math.floor(Math.random() * 10000)).padStart(4, '0')
  return `${year}${month}${day}${random}`
}

const calculateAmount = (item: GoodsItem) => {
  return (item.quantity || 0) * (item.unitPrice || 0)
}

const addGoodsItem = () => {
  invoiceForm.goods.push({
    name: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0
  })
}

const removeGoodsItem = (index: number) => {
  if (invoiceForm.goods.length > 1) {
    invoiceForm.goods.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个商品项')
  }
}

const goBack = () => {
  router.push('/invoice/list')
}

const saveDraft = async () => {
  try {
    // 保存草稿逻辑
    ElMessage.success('草稿已保存')
  } catch (error) {
    ElMessage.error('保存草稿失败')
  }
}

const previewInvoice = async () => {
  try {
    await invoiceFormRef.value?.validate()
    // 跳转到预览页面
    router.push({
      path: '/invoice/preview',
      query: { data: JSON.stringify(invoiceForm) }
    })
  } catch (error) {
    ElMessage.error('请完善必填信息后再预览')
  }
}

const nextStep = async () => {
  try {
    await invoiceFormRef.value?.validate()
    // 跳转到确认页面
    router.push({
      path: '/invoice/confirm',
      query: { data: JSON.stringify(invoiceForm) }
    })
  } catch (error) {
    ElMessage.error('请完善必填信息后再继续')
  }
}

const loadInvoiceData = async () => {
  // 模拟加载发票数据
  const mockData = {
    invoiceType: 'normal',
    invoiceNumber: generateInvoiceNumber(),
    issueDate: new Date().toISOString().split('T')[0],
    taxRate: '0.13',
    issuer: {
      name: '示例开票方有限公司',
      taxNumber: '91110000MA0012345678',
      address: '北京市朝阳区示例街道123号',
      phone: '010-12345678',
      bank: '中国工商银行北京分行',
      account: '1234567890123456789'
    },
    recipient: {
      name: '示例收票方有限公司',
      taxNumber: '91110000MA8765432109',
      address: '上海市浦东新区示例路456号',
      phone: '021-87654321',
      bank: '中国建设银行上海分行',
      account: '9876543210987654321'
    },
    goods: [
      {
        name: '示例商品',
        specification: '标准版',
        unit: '件',
        quantity: 1,
        unitPrice: 1000
      }
    ],
    remark: '示例备注信息'
  }
  
  Object.assign(invoiceForm, mockData)
}

// 生命周期
onMounted(() => {
  invoiceId.value = route.query.id as string || ''
  isEdit.value = !!invoiceId.value
  
  if (isEdit.value) {
    loadInvoiceData()
  } else {
    invoiceForm.invoiceNumber = generateInvoiceNumber()
    invoiceForm.issueDate = new Date().toISOString().split('T')[0]
  }
})
</script>

<style scoped>
.invoice-form-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.form-card {
  max-width: 1200px;
  margin: 0 auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.invoice-form {
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.add-btn {
  margin-left: auto;
}

.goods-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goods-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.goods-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  border-color: #409eff;
}

.goods-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.goods-number {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.goods-card-content {
  padding: 0;
}

.goods-card-content .el-form-item {
  margin-bottom: 20px;
}

.goods-card-content .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.amount-summary {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e4e7ed;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
}

.amount-item:last-child {
  border-bottom: none;
}

.amount-item.total {
  font-weight: 600;
  font-size: 16px;
  color: #e6a23c;
  border-top: 2px solid #e6a23c;
  margin-top: 10px;
  padding-top: 15px;
}

.amount-value {
  font-weight: 600;
  color: #303133;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invoice-form-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: center;
  }
}

@media (max-width: 480px) {
  .invoice-form {
    padding: 10px;
  }
  
  .form-section {
    padding: 15px;
  }
}
</style>
